/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.eurotrader.converters;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;


/**
 *
 * @author Usuário
 */
public class ConverteMoeda implements Converter {

    @Override
 public Object getAsObject(FacesContext facesContext,
         UIComponent uiComponent, String value) {

     FacesContext fc = FacesContext.getCurrentInstance();
     Locale l = fc.getViewRoot().getLocale();

     if (value != null) {
         value = value.trim();
         if (value.length() > 0) {
             try {
                 return new BigDecimal(NumberFormat.
                         getNumberInstance(l).parse(
                         value).doubleValue());
             } catch (ParseException e) {
                 e.printStackTrace();
             }
         }
     }
     return null;
 }

@Override
 public String getAsString(FacesContext facesContext,
         UIComponent uiComponent, Object value) {

     if (value == null) {
         return "";
     }
     if (value instanceof String) {
         return (String) value;
     }
     try {
       //  FacesContext fc = FacesContext.getCurrentInstance();
        // Locale l = fc.getViewRoot().getLocale();
         DecimalFormat formatador;
             formatador = new DecimalFormat("#,###,###,###,##0.00");
         formatador.setGroupingUsed(true);
         return formatador.format(value);

     } catch (Exception e) {
         throw new ConverterException("Formato não é número.");
     }
 }
}
